package com.lance.answer.gui.answer.gk.answer;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.lance.answer.gui.answer.AnswerObject;
import com.lance.answer.gui.answer.DealJsonString;
import com.lance.answer.gui.answer.Util;
import com.lance.answer.gui.answer.gk.DealInfoUtil;
import com.lance.answer.gui.answer.gk.answer.task.DoAnswerTask;
import com.lance.answer.util.Constant;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.*;
import java.util.concurrent.LinkedBlockingDeque;

/**
 *
 * 0616 ERP原理与应用  ERP原理与应用
 * 形考任务都没上传
 *
 * 审计学 形考得重新弄。
 * 液压气动技术
 */
@Slf4j
public class BatchDoAnswer {

    public static void main(String[] args) throws Exception {

       //   Thread.sleep(1000*60*60*2);
        //     Thread.sleep(7*62*60*1000);
            int sync = 16;

        // String teacher = "刘庆";
        //   String teacher = "李俊杰";
        //   String teacher = "艾";

        List<String> teachers = Lists.newArrayList();
        teachers.add("刘庆");
        teachers.add("李俊杰");
        teachers.add("艾");
        teachers.add("刘");
        // TODO 毛概的都没做
        teachers.add("李明");
        teachers.add("朱晓玉");
        teachers.add("宋柳萌");
        teachers.add("零散");

        Set<String> needAnswerSubject = Sets.newHashSet();

        Set<String> names = Sets.newHashSet();
        for (File file : new File("D:\\newAnswer\\deal1014").listFiles()) {
            System.err.println("file:"+file.getName());
            InputStream answerInputStream = new FileInputStream(file);
            String answerStr = IOUtils.toString(answerInputStream, "UTF-8");
            List<AnswerObject> list = JSONObject.parseArray(answerStr, AnswerObject.class);
            Map<String, AnswerObject> answers = new HashMap<>();
            Map<String, AnswerObject> originAnswers = new HashMap<>();
            for (AnswerObject answerObject : list) {
                answers.put(answerObject.getQuestionCode(), answerObject);
                originAnswers.put(DealJsonString.saveZhWord(answerObject.getQuestionTitle()), answerObject);
                if (answerObject.getAnswers() == null || answerObject.getAnswers().isEmpty()) {
                    System.err.println(file.getName() + "\t  code:" + answerObject.getQuestionCode());
                    names.add(file.getName());
                }
            }
        }


        LinkedBlockingDeque<AnswerDTO> answerQueue = new LinkedBlockingDeque<>();

        // 获取所有的用户名和密码
        // InputStream userInputStream = new FileInputStream("libs//allUser.txt");
        for (String teacher : teachers) {
            InputStream userInputStream = new FileInputStream("libs//teachers//" + teacher + ".user");
            List<String> userString = IOUtils.readLines(userInputStream, "utf-8");
            Map<String, String> usernameAndPwd = Maps.newHashMap();
            for (String user : userString) {
                String[] strs = user.split(",");
                String userCode = strs[0];
                String pwd = "";
                if (strs[1].length() < 18) {
                    pwd = strs[1];
                } else {
                    pwd = strs[1].substring(6, 14);
                    pwd = "Ouchn" + pwd;
                }
                usernameAndPwd.put(userCode, pwd);
            }


            // key = subjectName value 做题链接集合
            Map<String, Set<String>> mapBySubjectName = Maps.newHashMap();
         //   for (File f1 : Objects.requireNonNull(new File("libs//courseUrlInfo").listFiles())) {
            for (File f1 : Objects.requireNonNull(new File("libs//courseUrlInfo//").listFiles())) {
                Set<String> urlTaskSet = Sets.newHashSet();
                if (f1.length() < 50) {
                    continue;
                }
                String fileName = f1.getName();
                String subjectName = fileName.substring(0, fileName.length() - 4);
                List<String> urlInfoList = IOUtils.readLines(new FileInputStream(f1), "utf-8");
                for (String urlInfo : urlInfoList) {
                    if (urlInfo.contains("quiz")) {
                        if (urlInfo.contains("形考")
                                || urlInfo.contains("作业")
                                || urlInfo.contains("考核")
                                || urlInfo.contains("专题测验")
                                || urlInfo.contains("专题检验")
                              //  || urlInfo.contains("测试（")
                                || urlInfo.contains("材料分析题（")
                                || urlInfo.contains("综合记分作业")
                        ) {
                            if(urlInfo.contains("不计入")){
                                continue;
                            }
                            String urlTask = urlInfo.split(",")[0];
                            urlTaskSet.add(urlTask);
                        }
                    }

                }
                mapBySubjectName.put(subjectName, urlTaskSet);
            }

//        for(String kk:mapBySubjectName.keySet()){
//            if(kk.equals("建筑工程项目管理")){
//                System.err.println("22222222222222222222222222222222222222222222222222222222222222222");
//                System.out.println(mapBySubjectName.get(kk));
//            }
//        }


            for (String subjectName : mapBySubjectName.keySet()) {

                // 过滤掉英语
                if (Strings.isNullOrEmpty(subjectName) || subjectName.contains("英语")) {
                    continue;
                }
                if (mapBySubjectName.get(subjectName).size() < 1) {
                    continue;
                }
                log.info("subjectName:{}", subjectName);


                //
                // D:\newAnswer\deal1014
                File answerFile = new File("D:\\project\\answer-tool\\src\\main\\resources\\" + subjectName + "\\" + subjectName + "-answer.json");
                if (!answerFile.exists()) {
                    System.err.println(">>>>>>>>>>:" + subjectName);
                    answerFile = new File("D:\\newAnswer\\deal1014\\" + subjectName + "-answer.json");
                }
                if (!answerFile.exists()) {
                    System.err.println("??????????????11111111111111:" + subjectName);
                    log.info("{}需要拿到题目答案", subjectName);
                    needAnswerSubject.add(subjectName);
                    continue;
                }



                InputStream answerInputStream = new FileInputStream(answerFile);
                String answerStr = IOUtils.toString(answerInputStream, "UTF-8");
                List<AnswerObject> list = JSONObject.parseArray(answerStr, AnswerObject.class);
                Map<String, AnswerObject> answers = new HashMap<>();
                Map<String, AnswerObject> originAnswers = new HashMap<>();
                boolean hasEmptyAnswer = false;
                for (AnswerObject answerObject : list) {
                    answers.put(answerObject.getQuestionCode(), answerObject);
                    originAnswers.put(DealJsonString.saveZhWord(answerObject.getQuestionTitle()), answerObject);
                    if (answerObject.getAnswers() == null || answerObject.getAnswers().isEmpty()) {
                        if (DealInfoUtil.countUserCourseInfo("libs//userCourseInfo//" + teacher).get(subjectName) != null) {
                            System.err.println("有答案为空：：：" + subjectName + "\t" + answerObject.getQuestionCode() + "\t" + DealInfoUtil.countUserCourseInfo("libs//userCourseInfo//" + teacher).get(subjectName).size());
                        }
                        hasEmptyAnswer = true;
                        break;
                    }
                }
                if (hasEmptyAnswer) {
                    continue;
                }




                List<String> userNames = DealInfoUtil.countUserCourseInfo("libs//userCourseInfo//" + teacher).get(subjectName);

                if (userNames == null) {
                    continue;
                }

                for (String username : userNames) {
//
//                    if(!"1965001466883".equals(username)){
//                        continue;
//                    }

//               if(!Util.getVip().contains(username)){
//                   continue;
//               }
//               if(!"2136001453127".equals(username)){
//                   continue;
//               }


                    String pwd = usernameAndPwd.get(username);
                    AnswerDTO answerDTO = new AnswerDTO();
                    answerDTO.setSubjectName(subjectName);
                    answerDTO.setUsername(username);
                    answerDTO.setPwd(pwd);
                    answerDTO.setAnswers(answers);
                    answerDTO.setOriginAnswers(originAnswers);
                    answerDTO.setCommit(true);
                    answerDTO.setPush(false);
                    answerDTO.setAnswerUrl(Lists.newLinkedList(mapBySubjectName.get(subjectName)));
                    answerDTO.setTeacher(teacher);
                    // FIXME 过滤掉英语
                    if (subjectName.contains("英语")) {
                        continue;
                    }
//                    if(
//                            !subjectName.contains("社会调查研究与方法")
//                            &&!subjectName.contains("行政组织学")
//                            &&!subjectName.contains("民事诉讼法学")
//                    ){
//                        continue;液压与气压传动.txt
//                    }
                    // 还有高级财务会计
//                    if (subjectName.contains("机电控制工程基础")) { //两套URL
//                        continue;
//                    }
                    if (subjectName.contains("现代管理原理")) {
                        continue;
                    }
                    // todo
                    if (subjectName.contains("病理学与病理生理学")) {
                        continue;
                    }
                    if (subjectName.contains("机电控制与可编程序控制器技术")) {
                        continue;
                    }
                    if (subjectName.contains("审计学")) {
                        continue;
                    }
                    if(subjectName.equals("古代汉语(1)")){
                        continue;
                    }
                    if(subjectName.equals("建设监理")){
                        continue;
                    }
                    // 护理学基础 搞定  经济数学基础12 答案不一定完整 需要核验  外国文学 水力学(B) 政府经济学  现代货币金融学说  数据结构（本）
                    // 土木工程力学（本）  药理学（本） 古代诗歌散文专题  外科护理学  数据库应用技术  儿童家庭教育指导  儿童发展问题的咨询与辅导
//                    if (!subjectName.equals("儿童发展问题的咨询与辅导")) {
//                        continue;
//                    }
//                    if (!subjectName.contains("人类与社会")) {
//                        continue;
//                    }
//                    if (!subjectName.contains("药理学")) {
//                        continue;
//                    }
//                    if (!subjectName.contains("高级财务会计")) {
//                        continue;
//                    }
//               if (!subjectName.contains("毛泽东思想和中国特色社会主义理论体系概论")){
//                   continue;
//               }
                    //   if(!subjectName.equals("形势与政策")){
                    //   if(!subjectName.equals("中国近现代史纲要")){
                    //   if(!subjectName.equals("马克思主义基本原理概论")){
//               if(
//                       !subjectName.equals("习近平新时代中国特色社会主义思想")
//                       &&!subjectName.equals("思想道德修养与法律基础")
//                               &&!subjectName.equals("形势与政策")
//                               &&!subjectName.equals("思想道德与法治")
//                               &&!subjectName.equals("毛泽东思想和中国特色社会主义理论体系概论")
//                               &&!subjectName.equals("中国近现代史纲要")
//                               &&!subjectName.equals("马克思主义基本原理概论")
//               ){
//                   continue;
//               }
                    if (
                            subjectName.equals("习近平新时代中国特色社会主义思想")
                                    || subjectName.equals("思想道德修养与法律基础")
                                    || subjectName.equals("形势与政策")
                                    || subjectName.equals("思想道德与法治")
                                    || subjectName.equals("毛泽东思想和中国特色社会主义理论体系概论")
                                    || subjectName.equals("中国近现代史纲要")
                                    || subjectName.equals("马克思主义基本原理概论")
                    ) {
                        continue;
                    }
                 //   if (!subjectName.equals("公司财务")) {  //OK
               //     if (!subjectName.equals("西方经济学（本）")) { //OK
             //       if (!subjectName.equals("药事管理与法规（本）")) { //OK
             //       if (!subjectName.equals("学前儿童卫生与保健")) { // ok
                  //  if (!subjectName.equals("现代管理原理")) { // ok
//                    if (!subjectName.equals("病理生理学")) { // ok
//                        continue;
//                    }

                    // 社区护理学（本）  形考任务5还有问题，需要网上找。
                    // 西方经济学（本） 同上
                    // 药事管理与法规（本）（本） 同上

//               if(subjectName.equals("公司财务")){ // fixme 2022-6-6 这门课不能直接获取答案，需要网上找
//                   continue;

//               }
//               if(!subjectName.equals("钢结构（本）")){
//                   continue;
//               }
//               if(subjectName.equals("现代管理原理")){
//                   continue;
//               }
             //  if(subjectName.equals("学前儿童卫生与保健")){ //TODO
//               if(!subjectName.equals("西方行政学说")){
//                   continue;
//               }
                    answerQueue.add(answerDTO);
                }


            }



        }

        for(String name:needAnswerSubject){
            //  SUBJECT.put("学前儿童艺术教育(美术)","学前儿童艺术教育(美术)");
            System.out.println("SUBJECT.put(\""+name+"\",\""+name+"\");");
        }
//        System.err.println(answerQueue.size());
    //   Thread.sleep(2000000000);
        //    Thread.sleep(20000000);


        for (int i = 1; i <= sync; i++) {
            Thread answerThread = new DoAnswerTask(null, answerQueue);
            //log.info("加载课程ID：{} 名称：{} ", openCourseId,subjectName);
            answerThread.setName("答题线程--" + i);
            answerThread.start();
        }


    }


}
